<template>
  <page-layout>
    <!-- 顶部区域 -->
    <a-col :span="24">
      <a-card>
        <!-- 查询参数 -->
        <pro-query
          :searchParam="searchParam"
          @on-search ="search"
        ></pro-query>
      </a-card>
    </a-col>

    <!-- 中心区域 -->
    <a-col :span="24">
      <a-card>
        <a-button type="primary" class="editable-add-btn" @click="handleAdd">新增</a-button>
        <!-- 列表 -->
        <a-table bordered :columns="columns" :data-source="dataSource" :pagination="pagination" rowKey="id" ref="tableRef">
          <template v-for="col in ['wh', 'xdsj', 'tze', 'zy', 'zzq', 'pthzchou', 'zjlyuan', 'year', 'path']" #[col]="{ text, record }" :key="col">
            <div>
              <template  v-if="editableData[record.id] && ['wh', 'tze', 'zy', 'zzq', 'pthzchou', 'year'].includes(col)">
                <a-input v-model:value="editableData[record.id][col]" style="margin: -5px 0" />
              </template>
              <template v-else-if="editableData[record.id] && ['xdsj'].includes(col)">
                <a-date-picker v-model:value="editableData[record.id][col]" valueFormat="YYYY-MM-DD" style="width: 110px;"/>
              </template>
              <template v-else-if="editableData[record.id] && ['zjlyuan'].includes(col)">
                <a-select v-model:value="editableData[record.id][col]" style="width: 140px;">
                  <a-select-option value="上级下达">上级下达</a-select-option>
                  <a-select-option value="专项债">专项债</a-select-option>
                  <a-select-option value="政策性金融工具">政策性金融工具</a-select-option>
                  <a-select-option value="银行贷款">银行贷款</a-select-option>
                  <a-select-option value="地方一般债">地方一般债</a-select-option>
                </a-select>
              </template>
              <template v-else-if="editableData[record.id] && ['path'].includes(col)">
                <a-upload :action="`${http}/api/sys/oss/upload?bcpath=tzxd`" :multiple="false" :headers="headers" @change="handleChange">
                  <a-button type="primary" size="small">
                    <upload-outlined></upload-outlined>
                    上传
                  </a-button>
                </a-upload>
              </template>
              <template v-else>
                <div v-if="['path'].includes(col) && '' != text">
                  <a :href="`${http}/api/sys/oss/download?id=${text}`">投资下达文件下载</a>
                </div>
                <div v-else>{{ text }}</div>
              </template>
            </div>
          </template>

          <template #operation="{ record }">
            <div style="width: 100px;">
                <span class="editable-row-operations">
                <span v-if="editableData[record.id]">
                  <a @click="baocun(record.id)">保存</a>
                  <a-popconfirm title="确定取消吗？" @confirm="cancel(record.id)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a @click="edit(record.id)">编辑</a>
                </span>
              </span>
              <a-popconfirm
                v-if="dataSource.length"
                title="确定删除吗？"
                @confirm="onDelete(record.id)"
              >
                <a>删除</a>
              </a-popconfirm>
            </div>
          </template>
        </a-table>
      </a-card>
    </a-col>
  </page-layout>
</template>
<script setup>
  import {h, reactive, ref, toRaw} from 'vue';
  import {page, remove, save} from '@/api/module/tzxd_tzxd';
  import {cloneDeep} from "lodash-es";
  import {message} from "ant-design-vue";
  import moment from "moment/moment";
  import { v4 as uuidv4 } from "uuid";
  import global from '../global/global';
  import {list} from "@/view/qianqi/qqgz";

  const removeKey = "remove";
  const http = process.env.VUE_APP_API_BASE_URL;

  const tableRef = ref();
  const editableData = reactive({});
  /// 预览
  const imageFormat = {width: 34}
  /// 列配置
  const columns = [
    {dataIndex: "wh", key: "wh", title: "下达投资文号", slots: {customRender: 'wh'} },
    {dataIndex: "xdsj", key: "xdsj", title: "下达时间", slots: {customRender: 'xdsj'} },
    {dataIndex: "tze", key: "tze", title: "投资额（万元）", slots: {customRender: 'tze'} },
    {dataIndex: "zy", key: "zy", title: "中央（万元）", slots: {customRender: 'zy'} },
    {dataIndex: "zzq", key: "zzq", title: "自治区（万元）", slots: {customRender: 'zzq'} },
    {dataIndex: "pthzchou", key: "pthzchou", title: "配套或自筹（万元）", slots: {customRender: 'pthzchou'} },
    {dataIndex: "zjlyuan", key: "zjlyuan", title: "资金来源", slots: {customRender: 'zjlyuan'} },
    {dataIndex: "year", key: "year", title: "所属年份", slots: {customRender: 'year'} },
    {dataIndex: "path", key: "path", title: "文件预览", slots: {customRender: 'path'}},
    { key: 'operation', title: '操作', width: 100, slots: {customRender: 'operation'}},
  ];

  const dataSource = ref([]);
  page({"xmid": global.xmid}).then((response) => {
    dataSource.value = response.data.record;
  });

  /// 分页参数
  const pagination = {
    pageNum: 1,
    pageSize: 10,
  }

  /// 查询操作
  const search = function(value) {
    page({"zgqkuang": value.zgqkuang, "xmid": global.xmid}).then((response) => {
      dataSource.value = response.data.record;
    });
  }

  /// 查询参数
  const searchParam = [
    { key: 'wh', type: 'input', label: '下达投资文号' },
    { key: 'year', type: 'input', label: '所属年份' },
    /*{ key: 'year', type: 'yearPicker', label: '所属年份',
      mode: 'year', valueFormat: 'yyyy', format: 'yyyy', placeholder: '请选择年份'

    },*/
  ]

  const handleAdd = async () => {
    let xiangmu = await list({'id': global.xmid}).then((response)=>{
      return response.data;
    });
    let random = uuidv4().replaceAll("-", "");
    const addData = {
      id: random,
      xmid: xiangmu.id,
      wh: '',
      xdsj: '',
      tze: '',
      zy: '',
      zzq: '',
      pthzchou: '',
      zjlyuan: '',
      year: '',
      path: '',
    };
    dataSource.value.push(addData);
    edit(random);
  };

  const cancel = key => {
    delete editableData[key];
  };

  const onDelete = key => {
    dataSource.value = dataSource.value.filter(item => item.id !== key);
    remove({"id": key}).then((response) => {
      if(response.success){
        message.success({content: "删除成功", key: removeKey, duration: 1})
      } else {
        message.error({content: "删除失败", key: removeKey, duration: 1})
      }
    })
  };

  const edit = key => {
    editableData[key] = cloneDeep(dataSource.value.filter(item => key === item.id)[0]);
    handleKey = key
  };
  const baocun = key => {
    Object.assign(dataSource.value.filter(item => key === item.id)[0], editableData[key]);
    save(toRaw(editableData[key])).then((response) => {
      if(response.success){
        message.success({ content: '提交成功', duration: 1 })
      }else{
        message.error({ content: '提交失败', duration: 1 })
      }
    }).catch(error => {
      console.log('error', error);
    });

    delete editableData[key];
  };

  let yearShowOne;

  const openChange = (status) => {
    yearShowOne = status;
  }

  const panelChangeOne = (value) => {
    let nian = moment(value).format('YYYY');
    yearShowOne = false;
  }

  //文件上传
  const tokenKey = localStorage.getItem("token_key");
  const token = localStorage.getItem("token")
  const headers = {
    "Authorization": token,
    "Authorization-key": tokenKey
  };
  let handleKey;
  const handleChange = info => {
    let resFileList = [...info.fileList];
    let fileids = "";
    resFileList.map(file => {
      if (file.response) {
        file.url = file.response.data.path;
        if(fileids.length > 0){
          fileids += "," + file.response.data.id;
        } else {
          fileids += file.response.data.id;
        }
      }
      return file;
    });
    editableData[handleKey].path = fileids;
  }
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
